import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.List;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.io.file.*;
import javax.microedition.io.*;
import java.io.*;
import java.util.Enumeration;

public class TBrowser extends List implements CommandListener {
	protected String[] mDirs = new String[10];
	protected int mDirSize = 0;
	protected String mPath = "";
	protected CommandListener mParent;

	public TBrowser(CommandListener parentApp) {
		super("Выберите файл:", List.IMPLICIT);
		mParent = parentApp;
		setCommandListener(this); //sets a command listener
    getFileList();
	}
		
  protected void getFileList() {
    try {
			deleteAll();
			setTitle("/"+mPath);
      //Opens a file connection in READ mode
			Enumeration filelist = null;
			FileConnection fc = null;
			if(mPath!="") {
	      fc = (FileConnection)Connector.open("file:///"+mPath, Connector.READ);
    	  filelist = fc.list("*", true); //also hidden files are shown
			} else {
				filelist = FileSystemRegistry.listRoots();
			}
      String filename;
      append("..", null);
      while(filelist.hasMoreElements()) {
        filename = (String) filelist.nextElement();
				//                fc = (FileConnection)Connector.open("file:///"+mPath + filename, Connector.READ);
				append(filename, null);
      }   
			//            if(fc!=null) fc.close();
    }
    catch (IOException ioe) {
				//      Display.getDisplay(this).setCurrent(new Alert("IOException", ioe.getMessage(), null, AlertType.ERROR));
				//      System.out.println("IOException: "+ioe.getMessage());            
    }
    catch (SecurityException se) {
				//      Display.getDisplay(this).setCurrent(new Alert("SecurityException", se.getMessage(), null, AlertType.ERROR));
				//      System.out.println("SecurityException: "+se.getMessage());            
    }
  }
 
  public void commandAction(Command c, Displayable d) {
		if(c == List.SELECT_COMMAND) {
			String dir = getString(getSelectedIndex());
			if(dir=="..") {
				mPath = mPath.substring(0, mPath.length()-mDirs[--mDirSize].length());
			} else {
				mPath += dir;
				mDirs[mDirSize++] = dir;
			}
			getFileList();
		} else mParent.commandAction(c, d);
	}

}